//////////////////////////////////////////////////
// EASIM project
// easim.draw.FileMenu
// 6/7/2007 3:03 PM
// Cong Liu
// gzcong@gmail.com

// Copyright (C) 2007
// All rights reserved.
// Refer to LICENSE of JIST (Java In Simulation Time) for terms and conditions of use.

package easim.draw;

import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.JOptionPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.beans.XMLEncoder;
import java.beans.XMLDecoder;
import java.util.HashSet;
import java.util.Iterator;

public class FileMenu extends JMenu implements jist.runtime.JistAPI.DoNotRewrite
{
	private Frame frame;
	private JFileChooser fileChooser1;
	private JFileChooser fileChooser2;

	private void initFileChooser1() {
		this.fileChooser1 = new JFileChooser();
		this.fileChooser1.setCurrentDirectory(new File("."));
		this.fileChooser1.setFileFilter(new FileFilter() {
			public boolean accept (File file) {
				return file.getName().toLowerCase().endsWith(".xml") || 
					file.isDirectory();
			}
			public String getDescription() {
				return "XML files";
			}
	    });
	}

	private void initFileChooser2() {
		this.fileChooser2 = new JFileChooser();
		this.fileChooser2.setCurrentDirectory(new File("."));
		this.fileChooser2.setFileFilter(new FileFilter() {
			public boolean accept (File file) {
				return file.getName().toLowerCase().endsWith(".fig") || 
					file.isDirectory();
			}
			public String getDescription() {
				return "Fig files";
			}
	    });
	}

	public static Field openXML(String file) throws IOException {
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
		XMLDecoder decoder = new XMLDecoder(in);
		Field field = (Field)decoder.readObject();
		in.close();
		return field;
	}

	public static void saveXML(Field field, String file) throws IOException {
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
		XMLEncoder encoder = new XMLEncoder(out);
		encoder.writeObject(field);
		encoder.close();
		out.close();
	}

	public static void saveFig(Field field, String file) throws IOException {
    FigPainter painter = new FigPainter();
    painter.paint(field);
		BufferedWriter writer = new BufferedWriter(new FileWriter(file));
		writer.write(painter.toString());
		writer.close();
	}

	private void newDraw() {
		HashSet nodes = this.frame.field.getAllNodes();
    Iterator it = nodes.iterator();
    while (it.hasNext()) {
      Node node = (Node)it.next();
			this.frame.field.removeNode(node.id);
		}
		this.frame.selectedNode = null;
		this.frame.panel.repaint();
	}

	private void openXML() {
		this.fileChooser1.rescanCurrentDirectory();
		int result = this.fileChooser1.showOpenDialog(this.frame);
		if(result == JFileChooser.APPROVE_OPTION){
			File fp = fileChooser1.getCurrentDirectory();
			String file = fp.getPath() + fp.separator + 
				this.fileChooser1.getSelectedFile().getName();
			try {
				this.frame.field = openXML(file);
				this.frame.selectedNode = null;
				this.frame.panel.setPreferredSize(new Dimension(
					this.frame.field.width, this.frame.field.height));
				this.frame.pack();
				this.frame.validate();
				this.frame.panel.repaint();
			} catch (Exception ex) {
				JOptionPane.showMessageDialog(this.frame, ex.getMessage(),
					"ERROR", JOptionPane.ERROR_MESSAGE);
				ex.printStackTrace(System.out);
			}
		}
	}

	private void saveXML() {
		this.fileChooser1.rescanCurrentDirectory();
		int result = this.fileChooser1.showSaveDialog(this.frame);
		if(result == JFileChooser.APPROVE_OPTION){
			File fp = this.fileChooser1.getCurrentDirectory();
			String file = fp.getPath() + fp.separator + 
				this.fileChooser1.getSelectedFile().getName();
			String file2 = file.toLowerCase();
			if (! file2.endsWith(".xml")) file += ".xml";
			try {
				this.frame.field.width = this.frame.panel.getWidth();
				this.frame.field.height = this.frame.panel.getHeight();
				this.saveXML(this.frame.field, file);
			} catch (Exception ex) {
				JOptionPane.showMessageDialog(this.frame, ex.getMessage(),
					"ERROR", JOptionPane.ERROR_MESSAGE);
				ex.printStackTrace(System.out);
			}
		}
	}

	private void saveFig() {
		this.fileChooser2.rescanCurrentDirectory();
		int result = this.fileChooser2.showSaveDialog(this.frame);
		if(result == JFileChooser.APPROVE_OPTION){
			File fp = this.fileChooser2.getCurrentDirectory();
			String file = fp.getPath() + fp.separator + 
				this.fileChooser2.getSelectedFile().getName();
			String file2 = file.toLowerCase();
			if (! file2.endsWith(".fig")) file += ".fig";
			try {
				this.saveFig(this.frame.field, file);
			} catch (Exception ex) {
				JOptionPane.showMessageDialog(this.frame, ex.getMessage(),
					"ERROR", JOptionPane.ERROR_MESSAGE);
				ex.printStackTrace(System.out);
			}
		}
	}

	public FileMenu(Frame frame) {
		super("File");
		this.frame = frame;
		this.initFileChooser1();
		this.initFileChooser2();
		JMenuItem newDraw = new JMenuItem("New");
		JMenuItem openXML = new JMenuItem("Open");
		JMenuItem saveXML = new JMenuItem("Save As");
		JMenuItem saveFig = new JMenuItem("Export Fig");
		this.add(newDraw);
		this.add(openXML);
		this.add(saveXML);
		this.add(saveFig);
		newDraw.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				newDraw();
			}
		});
		openXML.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				openXML();
			}
		});
		saveXML.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				saveXML();
			}
		});
		saveFig.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				saveFig();
			}
		});
	}

}
